package com.samphanie.auiu.router.test;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author ZSY
 * <p>
 * 一个用原子类修饰， 一个用volatile修饰，在多线程的情况下做自增，然后输出最后的值
 */
public class AtomicDemo {

    public static void atomicTest() throws InterruptedException {

        AtomicTask atomicTask = new AtomicTask();

        Runnable runnable = () -> {
            for (int i = 0; i < 10000; i++) {
                atomicTask.incrementAtomic();
                atomicTask.incrementVolatile();
            }
        };

        Thread thread1 = new Thread(runnable);
        Thread thread2 = new Thread(runnable);
        thread1.start();
        thread2.start();

        thread1.join();
        thread2.join();

        System.out.println("原子类的结果： " + atomicTask.atomicInteger.get());
        System.out.println("volatile的结果： " + atomicTask.volatileCount);
    }

    static class AtomicTask {

        AtomicInteger atomicInteger = new AtomicInteger();
        volatile int volatileCount = 0;

        void incrementAtomic() {
            atomicInteger.getAndIncrement();
        }

        void incrementVolatile() {
            volatileCount++;
        }
    }

}
